﻿using Autofac;
using Microsoft.Extensions.DependencyInjection;
using Nasty.Core.Session;

namespace Nasty.Core.Registry
{
    public class ServiceLocator
    {
        private static IServiceProvider? _rootProvider { get; set; }

        public static void Registry(IServiceProvider rootProvider)
        {
            _rootProvider = rootProvider;
        }

        private static IServiceProvider? GetServiceProvider()
        {
            //优先当前环境的ServiceProvider;
            var currentProvider = AppSession.CurrentProvider.Value;
            if (currentProvider != null) return currentProvider;
            return _rootProvider;
        }

        public static T? Get<T>() where T : class
        {
            var serviceProvider = GetServiceProvider();
            if (serviceProvider == null) return null;
            return serviceProvider?.GetService<T>();
        }

        public static T? GetByName<T>(string name) where T : class
        {
            var serviceProvider = GetServiceProvider();
            if (serviceProvider == null) return null;

            // Autofac扩展：IComponentContext
            var context = serviceProvider.GetService<Autofac.IComponentContext>();
            return context?.ResolveNamed<T>(name);
        }

        public static T? GetByScope<T>(IServiceScope? scope = null) where T : class
        {
            var serviceProvider = GetServiceProvider();
            if (serviceProvider == null) return null;

            scope = scope == null ? serviceProvider.CreateScope() : scope;
            return scope.ServiceProvider.GetService<T>();
        }

        public static void NewScope(Action<IServiceScope?> action)
        {
            var serviceProvider = GetServiceProvider();
            var scope = serviceProvider?.CreateScope();
            action(scope);
        }
    }
}
